<template>
  <div>
    <!--面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域 -->
    <el-card>
      <!--添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!--角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!--展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdBottom',i1==0?'bdTop':'','vCenter']" v-for="(item1,i1) in scope.row.children"
                    :key="item1.id">
              <!--渲染一级权限 -->
              <el-col :span="5">
                <el-tag @close="removeRight(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!--渲染二、三级权限 -->
                <el-row :class="[i2===0?'':'bdTop','vCenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <!--渲染二权限 -->
                  <el-col :span="6">
                    <el-tag @close="removeRight(scope.row,item2.id)" closable type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!--渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag @close="removeRight(scope.row,item3.id)" closable type="warning"
                            v-for="(item3) in item2.children"
                            :key="item3.id">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!--索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRoles(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button @click="showSetRightDialog(scope.row)" size="mini" type="warning" icon="el-icon-setting">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--编辑角色的对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="setRoleDialogVisible"
      width="50%">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editRolesForm">确 定</el-button>
  </span>
    </el-dialog>
    <!--分配权限的对话框 -->
    <el-dialog
      @close="resetRightDialog"
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%">
      <!--树形控件 -->
      <el-tree ref="treeRef" node-key="id" default-expand-all :default-checked-keys="defKeys" show-checkbox
               :data="rightsList"
               :props="treeProps"></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点Id值数组
      defKeys: [],
      // 即将分配权限的角色Id
      roleId: '',
      // 控制编辑角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 获取所编辑角色的信息
      editForm: {},
      // 编辑角色的校验规则
      editFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表
    getRolesList: async function () {
      var { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败！')
      this.rolesList = res.data
    },
    // 根据ID删除指定权限
    removeRight: function (role, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        var { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败！')
        role.children = res.data
        this.$message.success('删除成功!')
      }).catch(() => {
        this.$message.info('已取消删除!')
      })
    },
    // 展示分配权限的对话框
    showSetRightDialog: async function (role) {
      this.roleId = role.id
      var { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限数据失败！')
      this.rightsList = res.data
      // 递归获取三级节点的Id
      this.getLeafList(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的方法,获取所有三级权限的Id,并保存到defKeys数组中
    getLeafList: function (node, arr) {
      // 如果当前节点不包含子节点那么就是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafList(item, arr)
      })
    },
    // 关闭对话框时重置 默认选中的节点Id值数组 中的数据
    resetRightDialog: function () {
      this.defKeys = []
    },
    // 点击为角色分配权限
    allotRights: async function () {
      var keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      var idStr = keys.join(',')
      var { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败！')
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    // 点击编辑按钮打开编辑对话框
    editRoles: async function (roleId) {
      var { data: res } = await this.$http.get('roles/' + roleId)
      if (res.meta.status !== 200) this.$message.error('获取角色信息列表失败！')
      this.editForm = res.data
      this.setRoleDialogVisible = true
    },
    // 点击确定按钮实现编辑角色
    editRolesForm: function () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return ''
        var { data: res } = await this.$http.put('roles/' + this.editForm.roleId, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('编辑角色失败！')
        this.getRolesList()
        this.setRoleDialogVisible = false
        this.$message.success('编辑角色成功！')
      })
    },
    // 点击删除按钮实现删除角色
    deleteRole: function (roleId) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        var { data: res } = await this.$http.delete('roles/' + roleId)
        if (res.meta.status !== 200) this.$message.error('删除失败！')
        this.getRolesList()
        this.$message.success('删除成功!')
      }).catch(() => {
        this.$message.info('已取消删除!')
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdTop {
    border-top: 1px solid #eee;
  }

  .bdBottom {
    border-bottom: 1px solid #eee;
  }

  .vCenter {
    display: flex;
    align-items: center;
  }
</style>
